# -*- coding: utf-8 -*-  
import numpy as np  
import scipy as sp  
import matplotlib.pyplot as plt 
import requests
import json
from requests import get,post,Session
import time
import datetime

class Trader:
    token = "";
    code = "";
    cookies = ""
    islogin = False
    cash = 0
    floatAmt = 0
    orders = []

    def init(self):
        self.login();
        self.code = self.query()[2]
        self.getcountinfo()
        self.orders = self.getorder()

    def update(self):
        self.getcountinfo()
        self.orders = self.getorder()

    def login(self):
        payload = {'clientVersion':'1.0.0','deviceImei':'F8E629DB-D306-4D44-B1A7-3C45A3E1F8C3'}
        payload["deviceModel"]="iPhone"
        payload["deviceVersion"]="9.3.5"
        payload["loginName"]="13148458056"
        payload["operator"]="310260894344346"
        payload["password"]="0D6B3B856DBA07F79BCE1496D8C643C4"
        payload["regSource"]="90012"
        payload["systemName"]="1"
        payload["version"]="0.0.1"
        r = requests.post("http://stock.oksdb.com/user/login", data=payload)
        txt = json.loads(r.text)
        self.token=txt["data"]["tokenInfo"]["token"]
        self.cookies = r.cookies
        return True

    def getcountinfo(self):
        r = requests.get("http://stock.oksdb.com/user/account/getAccountsInfo?token=" + self.token,cookies=self.cookies)
        j = json.loads(r.text)
        self.cash = j["data"][0]["amt"]
        self.floatAmt = j["data"][0]["floatAmt"]

    def query(self):
        data = {"futuresType":"CL"}
        r = requests.post("http://stock.oksdb.com/futuresquota/getCacheData",data)
        j = json.loads(r.text)
        return j["data"]["lastPrice"],j["data"]["percentage"],j["data"]["code"]
    # 0张，1空
    def buy(self,type = 0):
        # 获取时间
        t = self.gettime()
        price = self.query()[0]
        payload = {"orderData":"{'futuresCode' : '"+self.code+"','rate' : 7.1,'stopProfit' : 1800,'tradeType' :"+ str(type)+",'count' : 1,'couponIds' : '[]','traderId' : '13235','userBuyDate' : '" +t+"','userBuyPrice' : '"+str(price)+"'}"}
        payload["token"]=self.token
        payload["version"]="0.0.3"
        r = requests.post("http://stock.oksdb.com/order/futures/buy", data=payload)
        return r.text

    def getorder(self):
        payload = {"fundType":"1","futuresType":"1002"}
        payload["token"]=self.token
        r = requests.post("http://stock.oksdb.com/order/futures/posiList",payload)
        orders=[]
        lis = json.loads(r.text)["data"]["futuresScoreOrderList"]
        for order in lis:
            orders.append(order["id"])
        return orders

    def gettime(self):
        r = requests.post("http://stock.oksdb.com/user/sysTime")
        t = json.loads(r.text)
        return t["data"]["nowTime"]


    def sell(self,orderId):
        # 获取时间
        t = self.gettime()
        price = self.query()[0]
        payload={"shouldCheckPrice":"true"}
        payload["orderId"]="[{'orderId' : '','fundType' : '0'},{'orderId' : '" +str(orderId) + "','fundType' : '1'}]"
        payload["token"]=self.token
        payload["userSaleDate"]=t
        payload["userSalePrice"]=price
        payload["version"]="0.0.3"
        r = requests.post("http://stock.oksdb.com/order/futures/sale", data=payload)
        return r.text

    def sellall(self):
        orderstmp = self.getorder()
        self.sell(orderstmp)
    
    def sell(self,orderIds):
        if len(orderIds) <= 0:
            return "没有需要卖出的订单"
        # 获取时间
        t = self.gettime()
        price = self.query()[0]
        strids = ""
        for strid in orderIds:
            strids = strids + str(strid) + ","
        if strids[len(strids) -1] == ",":
            strids = strids[:-1]
        payload={"shouldCheckPrice":"true"}
        payload["orderId"]="[{'orderId' : '','fundType' : '0'},{'orderId' : '" +strids + "','fundType' : '1'}]"
        print(payload["orderId"])
        payload["token"]=self.token
        payload["userSaleDate"]=t
        payload["userSalePrice"]=price
        payload["version"]="0.0.3"
        r = requests.post("http://stock.oksdb.com/order/futures/sale", data=payload)
        return r.text
        
    def getcllist(self,ty):
        payload={"type":ty}
        payload["time"]=time.strftime("%Y%m%d%H%M%S",time.localtime())
        r = requests.post("http://stock.oksdb.com/futuresquota/list",data=payload)
        return r.text

tr = Trader()






